//
//  BLEManager.m
//  HDPatrolSystem
//
//  Created by hengdaliuyi on 16/3/28.
//  Copyright © 2016年 hengdawb. All rights reserved.
//

#import "BLEManager.h"
#import "PeripheralModel.h"

@implementation BLEmanager
@synthesize m_manger;
@synthesize m_peripheral;
@synthesize m_array_peripheral;
@synthesize mange_delegate;
@synthesize cbDiscoveryDelegate;



//单例
#undef	AS_SINGLETON
#define AS_SINGLETON( __class ) \
+ (__class *)sharedInstance;

#undef	DEF_SINGLETON
#define DEF_SINGLETON( __class ) \
+ (__class *)sharedInstance \
{ \
static dispatch_once_t once; \
static __class * __singleton__; \
dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } ); \
return __singleton__; \
}

static BLEmanager *sharedBLEmanger=nil;

+(BLEmanager *)shareInstance;
{
    @synchronized(self){
        if (sharedBLEmanger == nil) {
            sharedBLEmanger = [[self alloc]init];
        }
    }
    return sharedBLEmanger;
}

-(id)init
{
    self = [super init];
    if (self) {
        if (!m_array_peripheral) {
            m_manger = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
            m_array_peripheral = [[NSMutableArray alloc]init];
        }
    }
    return self;
}

//-(void)initCentralManger;
//{
//    m_manger = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
//}

#pragma mark
#pragma mark -------- Central Manager Delegate --------

- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
{
    if (central.state == CBCentralManagerStatePoweredOn) {
        self.cbCentralPoweredOn = YES;
    }
    if (central.state == CBCentralManagerStatePoweredOff) {
        NSLog(@"系统蓝牙关闭了，请先打开蓝牙");
        self.cbCentralPoweredOn = NO;

    }else{
        //可以自己判断其他的类型
        /*
         CBCentralManagerStateUnknown = 0,
         CBCentralManagerStateResetting,
         CBCentralManagerStateUnsupported,
         CBCentralManagerStateUnauthorized,
         CBCentralManagerStatePoweredOff,
         CBCentralManagerStatePoweredOn,
         */
    }
}

/*
 *这个方法是一旦扫描到外设就会调用的方法，注意此时并没有连接上外设，这个方法里面，你可以解析出当前扫描到的外设的广播包信息，当前RSSI等，现在很多的做法是，会根据广播包带出来的设备名，初步判断是不是自己公司的设备，才去连接这个设备，就是在这里面进行判断的
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
{
    NSString *localName = [advertisementData valueForKey:@"kCBAdvDataLocalName"];
    
    NSArray *services = [advertisementData objectForKey:@"kCBAdvDataServiceUUIDs"];
    
    if ([localName containsString:@"SmartPencil"])
    {
        BOOL isExist = [self comparePeripheralisEqual:peripheral RSSI:RSSI];
        if (!isExist)
        {
            PeripheralModel *l_per = [[PeripheralModel alloc]init];
            l_per.discoveredPeripheral = peripheral;
            l_per.m_peripheralIdentifier = [peripheral.identifier UUIDString];
            l_per.m_peripheralLocaName = localName;
            l_per.rssi = RSSI;
            l_per.m_peripheralServices   = [services count];
            [m_array_peripheral addObject:l_per];
            
            [cbDiscoveryDelegate discoveryDidRefresh];
        }
    }
    
}

/*
 *当连接到智慧笔以后，进入该代理方法
 */

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;
{
    [m_manger stopScan];
    NSLog(@"已经连接上了: %@",peripheral.name);
    [mange_delegate bleMangerConnectedPeripheral:YES]; //delegate 给出去外面一个通知什么的，表明已经连接上了
//    [m_peripheral discoverServices:nil]; //我们直接一次读取外设的所有的： Services ,如果只想找某个服务，直接传数组进去就行，比如你只想扫描服务UUID为 FFF1和FFE2 的这两项服务
}
/*
 *
 */
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;
{
    NSLog(@"链接外设失败");
}
/*
 *这个函数被调用是有前提条件的，首先你的要先调用过了 connectPeripheral:options:这个方法，
 其次是如果这个函数被回调的原因不是因为你主动调用了 cancelPeripheralConnection 这个方法，
 那么说明，整个蓝牙连接已经结束了，不会再有回连的可能，得要重来了
 */
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;
{
    NSLog(@"Central didDisconnectPeripheral");
    
    //如果你想要尝试回连(重新连接)外设，可以在这里调用一下链接函数
    /*
     [central connectPeripheral:peripheral options:@{CBCentralManagerScanOptionSolicitedServiceUUIDsKey : @YES,CBConnectPeripheralOptionNotifyOnDisconnectionKey:@YES}];
     */
    [mange_delegate bleMangerDisConnectedPeripheral:peripheral];
}

-(BOOL) comparePeripheralisEqual :(CBPeripheral *)disCoverPeripheral RSSI:(NSNumber *)RSSI
{
    if ([m_array_peripheral count]>0) {
        for (int i=0;i<[m_array_peripheral count];i++) {
            PeripheralModel *l_per = [m_array_peripheral objectAtIndex:i];
            if ([disCoverPeripheral isEqual:l_per.discoveredPeripheral]) {
                l_per.rssi = RSSI;
                return YES;
            }
        }
    }
    return NO;
}

- (void) startScanning
{
    
    if((NSInteger)[m_manger state] == CBCentralManagerStatePoweredOn)
    {
        NSDictionary *options=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO],CBCentralManagerScanOptionAllowDuplicatesKey, nil];
        [m_manger scanForPeripheralsWithServices:nil options:options];
    }
    /*
     关于手机蓝牙其他状态判断
    else if ([m_manger state] == CBCentralManagerStateUnsupported){}
     */
}

- (void) stopScanning
{
    [m_manger stopScan];
    [self clearDevices];
}

- (void) clearDevices
{
    [m_array_peripheral removeAllObjects];
 
}


@end
